<template>
    <div class="mb-0">
        <el-upload :class="disabled ? 'c-disabled' : ''" action="/api/shop/admin/upload" name="uploadFile" :accept="accept.join(',')" multiple :disabled="disabled" :list-type="listType" :on-progress="handleProgress" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleSuccess" :on-exceed="handleExceed" :limit="limit" :show-file-list="showFileList" :file-list="echo">
            <i v-if="listType === 'picture-card'" class="el-icon-plus" slot="trigger"></i>
            <div>
                <el-button :disabled="disabled" v-if="listType === 'text'" slot="trigger" size="small" :type="buttonType">{{ buttonName }}</el-button>
            </div>
            <div slot="tip" v-if="tip && !disabled && tip.length > 0">
                <div v-for="(item, index) in tip" :key="index">
                    <span v-if="tip.length > 1">{{ index + 1 }}.</span>
                    <span>{{ item }}</span>
                </div>
            </div>
        </el-upload>

        <ElImageViewer class="viewer" v-if="index >= 0" :on-close="handleCloseViewer" :url-list="list" :initialIndex="index" />
    </div>
</template>
<script>
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
export default {
    components: {
        ElImageViewer,
    },
    props: {
        buttonType: {
            type: String,
            default: "default"
        },
        value: {
            type: [String, Array],
            default: "",
        },
        limit: {
            type: Number,
            default: 1000,
        },
        listType: {
            type: String,
            default: "picture-card",
        },
        buttonName: {
            type: String,
            default: "上传文件",
        },
        disabled: {
            type: Boolean,
            default: false,
        },
        // 是否展示文件
        showFileList: {
            type: Boolean,
            default: true,
        },

        tip: {
            type: Array,
            default: () => [],
        },
        accept: {
            type: Array,
            default: () => [],
        },
    },
    model: {
        prop: "value",
        event: "change",
    },
    data () {
        return {
            list: [],
            //   回显
            echo: [],
            index: -1,
        };
    },
    mounted () {
        const unwatch = this.$watch(
            "value",
            function (newValue) {
                if (this.list.length <= 0 && newValue) {
                    const echo = [];
                    if (newValue.constructor === String) {
                        this.list.push(newValue);
                        echo.push({
                            name: this.getFileName(newValue),
                            url: newValue,
                        });
                        this.echo = JSON.parse(JSON.stringify(echo));
                    } else if (newValue.constructor === Array) {
                        this.list = newValue;
                        for (let i = 0; i < newValue.length; i++) {
                            echo.push({
                                name: this.getFileName(newValue[i]),
                                url: newValue[i],
                            });
                        }
                        this.echo = JSON.parse(JSON.stringify(echo));
                    }
                }
                try {
                    unwatch();
                } catch (error) { }
            },
            { immediate: true }
        );
    },
    methods: {
        handleSuccess (response) {
            if (response.result) {
                this.list.push(response.result.url);
                if (this.limit === 1) {
                    // 一张图片直接返回字符串
                    this.$emit("change", response.result.url);
                } else {
                    this.$emit("change", this.list);
                }
            } else {
                this.echo = [];
                this.list = [];
                this.$message.warning("上传失败！");
            }
        },
        handleRemove (file) {
            const index = this.onFileIndex(file);
            this.list.splice(index, 1);
            if (this.limit === 1) {
                // 一张图片直接返回字符串
                this.$emit("change", "");
            } else {
                this.$emit("change", this.list);
            }
        },
        handleExceed () {
            this.$message.warning(`超出最大上传数量${this.limit}`);
        },
        handleCloseViewer () {
            this.index = -1;
        },
        handlePictureCardPreview (file) {
            if (this.listType === "text") {
                window.open(this.list[this.onFileIndex(file)]);
            } else if (this.listType === "picture-card") {
                this.index = this.onFileIndex(file);
            }
        },
        handleProgress (event, file, fileList) {
            // file.name = `附件`;
        },
        getFileName (url) {
            try {
                if (url) {
                    return url.split("/").pop();
                }
            } catch (error) {
                return "获取失败！";
            }
        },
        onFileIndex (file) {
            let url;
            if (file.status === "success") {
                if (file.response && file.response.result) {
                    url = file.response.result.url;
                } else {
                    url = file.url;
                }
            }
            return this.list.findIndex((x) => x === url);
        },
    },
};
</script>
<style scoped lang="scss">
.viewer {
    z-index: 99999 !important;
}

/deep/ .c-disabled {
    .el-upload--picture-card {
        border: 1px solid #e4e7ed !important;
        background: #f5f7fa !important;
        display: none;
    }
    .el-upload--text {
        display: none;
    }
}
</style>
